import React, { useEffect } from 'react';
import {
  Drawer,
  Form,
  Input,
  DatePicker,
  Select,
  Radio,
  Switch,
  Button,
} from 'antd';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

const BookDrawer = ({ visible, mode, onClose, onConfirm, book, fetchData }) => {
  const [form] = Form.useForm();
  const initialValues = {
    title: mode === 'edit' ? book?.title : '',
    tags: mode === 'edit' ? book?.tags.split(',') : '',
    type: mode === 'edit' ? book?.type : '',
    status: mode === 'edit' ? book?.status : '',
    date: mode === 'edit' && book?.date ? moment(book.date) : null,
    author: mode === 'edit' ? book?.author : '',
    isPublic: mode === 'edit' ? book?.isPublic : false,
  };

  useEffect(() => {
    form.setFieldsValue(initialValues);
  }, [initialValues, form]);

  const handleConfirm = () => {
    form
      .validateFields()
      .then(values => {
        const requestOptions = {
          method: mode === 'add' ? 'POST' : 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            ...values,
            tags: Array.isArray(values.tags)
              ? values.tags.join(',')
              : values.tags,
            date: moment(values.date).format('YYYY-MM-DD HH:mm:ss'),
            type: Array.isArray(values.type)
              ? values.type.join(',')
              : values.type,
          }),
        };

        const url =
          mode === 'add'
            ? `http://localhost:29157/api/book/list?token=${sessionStorage.getItem(
                'token'
              )}`
            : `http://localhost:29157/api/book/list/${
                book.id
              }?token=${sessionStorage.getItem('token')}`;
        fetch(url, requestOptions)
          .then(response => response.json())
          .then(data => {
            onConfirm(values);
            form.resetFields();
            fetchData();
            onClose();
          })
          .catch(error => {
            console.error('Error:', error);
          });
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  const handleCancel = () => {
    form.resetFields();
    onClose();
  };

  return (
    <Drawer
      title={mode === 'add' ? '新增书籍' : '编辑书籍'}
      width={720}
      onClose={handleCancel}
      visible={visible}
      bodyStyle={{ paddingBottom: 80 }}
      footer={
        <div
          style={{
            textAlign: 'right',
          }}>
          <Button
            onClick={handleCancel}
            style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button
            onClick={handleConfirm}
            type='primary'>
            确定
          </Button>
        </div>
      }>
      <Form
        layout='vertical'
        form={form}
        initialValues={initialValues}>
        <Form.Item
          name='title'
          label='书名'
          rules={[{ required: true, message: '请输入书名' }]}>
          <Input placeholder='请输入书名' />
        </Form.Item>

        <Form.Item
          name='tags'
          label='标签'
          rules={[{ required: true, message: '请输入标签' }]}>
          <Select
            mode='tags'
            style={{ width: '100%' }}
            placeholder='请输入标签，用逗号分隔'
            tokenSeparators={[',']}
          />
        </Form.Item>

        <Form.Item
          name='type'
          label='类型'
          rules={[{ required: true, message: '请选择类型' }]}>
          <Select
            mode='tags'
            style={{ width: '100%' }}
            placeholder='请输入类型，用逗号分隔'
            tokenSeparators={[',']}
          />
        </Form.Item>

        <Form.Item
          name='status'
          label='状态'
          rules={[{ required: true, message: '请选择状态' }]}>
          <Radio.Group defaultValue='待阅读'>
            <Radio value='已阅读'>已阅读</Radio>
            <Radio value='待阅读'>待阅读</Radio>
            <Radio value='阅读中'>阅读中</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name='date'
          label='时间'
          rules={[{ required: true, message: '请选择时间' }]}>
          <DatePicker
            showTime
            style={{ width: '100%' }}
          />
        </Form.Item>
        <Form.Item
          name='author'
          label='作者'
          rules={[{ required: true, message: '请输入作者' }]}>
          <Input placeholder='请输入作者' />
        </Form.Item>
        <Form.Item
          name='isPublic'
          label='是否公开'
          valuePropName='checked'>
          <Switch />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default BookDrawer;
